package org.nowcoder.leetcode.BTree;

/**
 * Title  : 654. Maximum Binary Tree
 * Source : https://leetcode.cn/problems/maximum-binary-tree/description/
 * Author : XrazYang
 * Date   : 2024-04-26
 */

public class LeetCode_654 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    private TreeNode dfs(int[] nums, int left, int right) {
        int max = -1, index = -1;
        for (int i = left; i <= right; i++) {
            if (max < nums[i]) {
                max = nums[i];
                index = i;
            }
        }
        if (max != -1) {
            TreeNode root = new TreeNode(max);
            root.left = dfs(nums, left, index - 1);
            root.right = dfs(nums, index + 1, right);
            return root;
        }
        return null;
    }

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return dfs(nums, 0, nums.length - 1);
    }
}
